<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <el-form :model="userForm" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="头像">
          <el-upload class="avatar-uploader" action="/api/Userfile/upload" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" :headers="uploadHeaders">
            <img v-if="userForm.avatar" :src="`/api/Userfile/${userForm.avatar}`" class="avatar">
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="userForm.name"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="不修改请留空"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="userForm.confirmPassword" type="password" placeholder="不修改请留空"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-tag>{{ userForm.role === 'user' ? '用户' : '管理员' }}</el-tag>
        </el-form-item>
        <el-form-item label="创建时间">
          <span>{{ userForm.created_at }}</span>
        </el-form-item>
        <el-form-item label="更新时间">
          <span>{{ userForm.updated_at }}</span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveUserInfo">保存修改</el-button>
          <el-button type="danger" @click="handleLogout">退出登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useRouter } from 'vue-router'

const router = useRouter()
const formRef = ref(null)

const validatePass = (rule, value, callback) => {
  if (userForm.value.password && !value) {
    callback(new Error('请再次输入密码'))
  } else if (value !== userForm.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [{ validator: validatePass, trigger: 'blur' }]
}

const userForm = ref({
  id: '',
  username: '',
  name: '',
  avatar: '',
  role: '',
  created_at: '',
  updated_at: '',
  password: '',
  confirmPassword: ''
})

const uploadHeaders = {
  Authorization: localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : ''
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    userForm.value.avatar = response.data
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.msg || '上传失败')
  }
}

const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('userInfo')
  ElMessage.success('退出登录成功')
  router.push('/login')
}

const saveUserInfo = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const updateData = {
      ...userForm.value
    }
    
    if (!updateData.password) {
      delete updateData.password
      delete updateData.confirmPassword
    }
    
    const now = new Date()
    updateData.updated_at = now.toISOString()
    
    const res = await request.post('/users/addadmin', {
      ...updateData,
      type: 'edit'
    })

    if (res.code === 200) {
      ElMessage.success('保存成功')
      const updatedUserInfo = {
        ...userForm.value,
        password: undefined,
        confirmPassword: undefined,
        updated_at: now.toISOString()
      }
      localStorage.setItem('userInfo', JSON.stringify(updatedUserInfo))
      window.location.reload()
    } else {
      ElMessage.error(res.msg || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

onMounted(() => {
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    const userInfo = JSON.parse(storedUserInfo)
    Object.assign(userForm.value, userInfo)
  }
})
</script>

<style scoped>

.profile-card {
  max-width: 800px;
  margin: 0 auto;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}

.avatar-uploader .avatar-uploader-icon:hover {
  border-color: #409EFF;
}
</style>